package com.idiot.service.impl;

import com.github.pagehelper.Page;

import com.idiot.domain.common.exceptions.MyException;
import com.idiot.domain.common.utils.IdGen;
import com.idiot.domain.dao.IMenuDao;
import com.idiot.domain.model.Menu;
import com.idiot.service.IMenuService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by idiot on 2016/12/13.
 */
@Service
public class MenuServiceImpl implements IMenuService{
    @Resource
    private IMenuDao menuDao;


    @Override
    public List<String> getPermissionsByUserId(long userId) {
        List<Menu> list = menuDao.getMenusByUserId(userId);
        List<String> permissions = new ArrayList<String>();
        if(list != null && !list.isEmpty()){
            for (Menu menu : list) {
                if(StringUtils.isNotBlank(menu.getPermission()))
                    permissions.add(menu.getPermission());
            }
        }
        return permissions;
    }

    @Override
    public List<Menu> getMenusByParenrId(long parentId) {
        return menuDao.getMenusByParenrId(parentId);
    }

    @Override
    public List<Menu> getFirstLevelMenusByUserId(long userId) {
        return menuDao.getFirstLevelMenusByUserId(userId);
    }

    @Override
    public Page<Menu> getAllPageMenus(RowBounds rowBounds) {
        Page<Menu> list = menuDao.getAllPageMenus(rowBounds);
        //遍历集合  获取父级菜单名称
        for(Menu menu : list){
            if(menu.getParentId() != 0){
                Menu parentMenu = menuDao.getMenuByMenuId(menu.getParentId());
                menu.setParentName(parentMenu.getMenuName());
            }
        }
        return list;
    }

    @Override
    public void insert(Menu info) {
        info.setMenuId(IdGen.get().nextId());   //设置menuId
        if(menuDao.insert(info) < 1){
            throw new MyException("新增菜单信息失败");
        }
    }

    @Override
    public void update(Menu info) {
        if(menuDao.update(info) < 1){
            throw new MyException("修改菜单信息失败");
        }
    }

    @Override
    public Menu getMenuByMenuId(long menuId) {
        return menuDao.getMenuByMenuId(menuId);
    }

    @Override
    public void delete(long menuId) {
        if(menuDao.delete(menuId) < 1){
            throw new MyException("删除菜单信息失败");
        }
    }

    @Override
    public List<Menu> getAllMenus() {
        return menuDao.getAllMenus();
    }

    @Override
    public List<Menu> getAllFirstMenus() {
        return menuDao.getAllfirstMenus();
    }

}
